from flask import (
    Blueprint,
    Flask,
    Response,
    jsonify,
    make_response,
    request,
    redirect,
    url_for,
    render_template,
    flash,
)
from flask_sqlalchemy import SQLAlchemy
from flask_login import (
    LoginManager,
    UserMixin,
    current_user,
    login_user,
    login_required,
    logout_user,
)
from werkzeug.security import generate_password_hash, check_password_hash
from ..baseapp import app, db
import logging

logger = logging.getLogger(__name__)
bp_login_mgr = Blueprint("login_mgr", __name__, url_prefix="/login_mgr")

login_manager = None


def set_login_manager(app):
    global login_manager
    login_manager = LoginManager(app)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))  # 密码的哈希值


@app.route("/admin_init", methods=["GET", "POST"])
def admin_init():
    # 如果User中已有
    existing_admin = User.query.filter_by(username="admin").first()
    if existing_admin:
        flash("管理员用户已存在，不得注册")
        return redirect(url_for("login"))
    if request.method == "POST":
        password = request.form["password"]
        existing_admin = User.query.filter_by(username="admin").first()

        if existing_admin:
            flash("管理员账号admin已存在")  # 需导入flash模块
            return redirect(url_for("admin_init"))

        # 密码哈希加密存储[1,5](@ref)
        hashed_password = generate_password_hash(password, method="pbkdf2:sha256")
        new_user = User(username="admin", password=hashed_password)

        try:
            db.session.add(new_user)
            db.session.commit()
            flash("管理员初始化成功，请登录")
            return redirect(url_for("login"))
        except Exception as e:
            db.session.rollback()
            flash("管理员初始化失败，请重试")

    return render_template("admin_init.html")


@app.route("/has_access", methods=["GET"])
# @login_required
def has_access():
    """
    验证用户是否具有该环境的权限
    """

    # 获取X-Original-URI的值
    x_original_uri = request.headers.get("X-Original-URI")
    if current_user.is_authenticated:
        print("user_login", current_user.username, current_user.id, x_original_uri)
    else:
        return jsonify({"error": "Not login"}), 401

    # TODO: Verification of User name
    print("user_login", current_user.username, current_user.id, x_original_uri)
    if current_user.username:
        resp = make_response('{"has_access": true}')
        print("cache-control header:", resp.headers.get("Cache-Control"))
        resp.headers["Cache-Control"] = "public, max-age=30"
        return resp, 200
    else:
        return jsonify({"has_access": False}), 401
    # return render_template("login.html")


# 修改登录验证逻辑
@app.route("/login", methods=["GET", "POST"])
def login():
    """
    处理用户登录
    如果目前没有admin用户，就redirect到admin_init
    """
    if not User.query.filter_by(username="admin").first():
        return redirect(url_for("admin_init"))
    # If user is logged in, redirect to dashboard
    if current_user.is_authenticated:
        return redirect(url_for("container_mgr.dashboard"))
    redirect_target = request.args.get("redirect", "")
    redirect_target = redirect_target.removeprefix('"').removesuffix('"')
    logger.info(f"redirect target is: {redirect_target}")

    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):  # 哈希验证[1](@ref)
            login_user(user)
            if redirect_target:

                return redirect(redirect_target)
            return redirect(url_for("container_mgr.dashboard"))
        flash("用户名或密码错误")
    return render_template("login.html")


@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("login"))


@app.route("/add_user", methods=["POST"])
def add_user():
    data = request.get_json()
    username = data["username"]
    password = data["password"]
    existing_user = User.query.filter_by(username=username).first()

    if username == "admin":
        flash("Cannot add or modify the admin user")
        return redirect(url_for("add_user"))

    if existing_user:
        flash("该用户名已被注册")
        return redirect(url_for("add_user"))

    hashed_password = generate_password_hash(password, method="pbkdf2:sha256")
    new_user = User(username=username, password=hashed_password)

    try:
        db.session.add(new_user)
        db.session.commit()
        flash("用户添加成功")
        return redirect(url_for("login"))
    except Exception as e:
        db.session.rollback()
        flash("用户添加失败，请重试")
        return redirect(url_for("add_user"))


@app.route("/user_info", methods=["GET", "POST"])
@login_required
def user_info():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"].strip()

        if current_user.username == "admin" and username != "admin":
            flash("Cannot modify the admin user's name!")
            return redirect(url_for("user_info"))

        if password == "":
            flash("Password cannot be empty!")
            return redirect(url_for("user_info"))

        user = User.query.get(current_user.id)
        user.username = username

        # 记住之前的密码
        user.password = generate_password_hash(password, method="pbkdf2:sha256")

        try:
            db.session.commit()
            flash("用户更新成功")
            return redirect(url_for("login"))
        except Exception as e:
            db.session.rollback()
            flash("用户更新失败，请重试")
            return redirect(url_for("user_info"))

    return render_template("user_info.html")


@app.route("/update_user/<int:user_id>", methods=["POST"])
@login_required
def update_user(user_id):
    print(current_user.username)
    if current_user.username != "admin":
        return jsonify({"error": "You are not the admin to perform this action"}), 400
    user = User.query.get(user_id)
    if not user:
        return jsonify({"error": f"User #{user_id} is not exist!"}), 400
    data = request.get_json()
    password = data["password"]
    if user.username == "admin":
        return (
            jsonify(
                {
                    "error": f"Cannot modify the admin user! Admin should change in the user info page."
                }
            ),
            400,
        )

    user.password = generate_password_hash(password, method="pbkdf2:sha256")

    try:
        db.session.commit()
        return jsonify({"error": f"User Modified!"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": f"Failed to update user!"}), 400


@app.route("/get_all_users", methods=["GET"])
def get_all_users():
    users = User.query.all()
    user_list = [{"id": user.id, "username": user.username} for user in users]
    return {"users": user_list}


# 修改登录验证逻辑
@app.route("/users_manage", methods=["GET", "POST"])
@login_required
def route_users_management():
    return render_template("users_manage.html")
